import WxService from './assets/plugins/wx-service/WxService'
import WxValidate from './assets/plugins/wx-validate/WxValidate'

import Api from './utils/api'
import Util from './utils/util'

//app.js
App({
  globalData: {        
    //支付要用的
    code: null,
    openid: null,
    session_key: null,


    //正式环境（去微信调用接口用的）
    appid: 'wx11c899fc27f1ea98',

    //版本号
    version:'v1.2.6',

    
  //测试环境
  //app_id: 'bcc1cf2e-b376-11e5-921c-fcaa1490ccaf',
  //private_key: '690b98fcb37711e5921cfcaa1490ccaf717130d1b37711e5921cfcaa1490ccaf',

  //app_id: 'c109ab0e-de11-11e7-a9db-00163e010763',
  //private_key:'742e2e4018faad1aae6a47f7388738c143d9cde03f34199d288e6cd22d4449ea86906ff1',


  //正式环境 小程序使用(去服务端取app_token用)
  app_id: 'c109ab0e-de11-11e7-a9db-00163e010763',
  private_key:'742e2e4018faad1aae6a47f7388738c143d9cde03f34199d288e6cd22d4449ea86906ff1',



    //网络连接情况
    isConnected:true,

    hasLogin: false,

    userInfo: {},
    city: null,//城市


    //用户信息
    memberInfo: '',

    // memberInfo: {
    //   member_id: "12803016",
    //   mobile: "18771786450",
    //   payment_password_flag: "N",
    //   small_direct_flag: "N",
    //   sms_notify_flag: "N",
    //   user_id: "bc239c05582d4438ad897ae865e489f7",
    //   security_code: "g3whjvd3",
    //   //user_token和app_token差不多
    //   //app_token: "44d8f578f77c7efad164c237eb05cd492e227a017523b65b8392e7ddc6d1a0b0ab4443bf8fab900540afad3276823471"
    // },

    //地址信息
    locationInfo: {
      //latitude: "39.90403",
      //longitude: "116.407526",
      latitude: "40.05",
      longitude: "116.30",
      speed: "-1",
      accuracy: "65",
      altitude: "0",
      verticalAccuracy: "65",
      horizontalAccuracy: "65",
      errMsg: "ok"
    },

    //百度地图 开放平台 访问应用（AK）
    //ak: 'ADPGZaYLluqS5tD5wjC0c5rNYTQMMwEQ',//开发环境用
    ak: 'td3lyUiouRca949q9aUgZ2rexIPBBpvw', //正式环境用



    //根据经纬度获取详细地址
    CurrentDetailAddress: '',


    //用户是否取消登录
    userCancellLogin: false,


    //订单列表传参switchTab
    secondIndex: "",
    status: "",
    order_data: "",
    num:1
  },



  //启动
  onLaunch: function () {
    console.log('App onLaunch')



    // 监听网络状态变化

    wx.onNetworkStatusChange(res => {
      console.log("########监控网络变化##########")
      console.log(res)
      console.log(res.isConnected)
      this.globalData.isConnected = res.isConnected
    })



    try {
      var res = wx.getStorageInfoSync()
      console.log("%%%%%%%%%%%%%%     本地的缓存 keys     %%%%%%%%%")
      console.log(res.keys)
      console.log("currentSize>>>" + res.currentSize)
      console.log("limitSize>>>" + res.limitSize)
      console.log(" getStorageInfo end>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
    } catch (e) {
      // Do something when catch error
    }



    /* 判断本地缓存有没有memberInfo,如果有，则存入全局变量 hasLogin = true */
    try {
      var memberInfo = wx.getStorageSync('memberInfo')
      console.log("-----------本地缓存的数据 memberInfo----------------")
      console.log(memberInfo)

      if (memberInfo) {
        this.globalData.memberInfo = memberInfo
        this.globalData.hasLogin = true
      }

      var userInfo = wx.getStorageSync('userInfo')
      console.log("-----------本地缓存的数据 userInfo----------------")
      console.log(userInfo)

    } catch (e) {
      // Do something when catch error
    }

    /* 判断版本情况 */

    try {

      var version = wx.getStorageSync('version')
      console.log("get version>>>>>" + version)
      if (version) {
        console.log("get VersionNum >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
        console.log(Util.getVersionNum(version))
        console.log(Util.getVersionNum(this.globalData.version)) 
        if (Util.getVersionNum(version) < Util.getVersionNum(this.globalData.version)) {
          /* 此处考虑清除缓存 */
          console.log("################ 缓存区版本过旧！ 清除本地缓存  ################")
          wx.clearStorageSync()

        }
      } else {
        console.log("################ 将版本号放入本地缓存 ################")
        wx.setStorageSync('version', this.globalData.version)

      }
    } catch (e) {
      console.log(e)
    }



    //获得app_token和安全码security_code
/*     const data = {
      app_id: this.globalData.app_id,
      private_key: this.globalData.private_key,
    };

    Api.getTokenAndCode({
      data,
      success: (res) => {

        console.log(res)
        console.log("========================================")
        console.log("---获得app_token和安全码security_code---")
        console.log("app_token:" + res.data.data.app_token)
        console.log("security_code:" + res.data.data.security_code)
        console.log("")

        console.log(res)
        console.log(res)

        if (res.data.rsp_code == 'succ') {
          this.globalData.app_token = res.data.data.app_token;
          this.globalData.security_code = res.data.data.security_code;
        } else if (res.data.rsp_code == 'fail') {
          console.log(res.data.error_code)
          console.log(res.data.error_msg)
        }

      }
    })
 */


    // 获取用户信息

    /* (关键) 获取userInfo start */
    this.getUserInfo()
    /* (关键) 获取userInfo end */


    //调用地理信息
    this.getLocation()


    /*     console.log("------------ onLaunch wx.getSetting res-------------")
        console.log("------------ onLaunch wx.getSetting res-------------")
    
    
        wx.getSetting({
          success: res => {
            console.log("------------ onLaunch wx.getSetting res-------------")
            console.log(res)
    
            if (res.authSetting['scope.userInfo']) {
              // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
              wx.getUserInfo({
                success: res => {
                  // 可以将 res 发送给后台解码出 unionId
                  this.globalData.userInfo = res.userInfo
    
                  // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                  // 所以此处加入 callback 以防止这种情况
                  if (this.userInfoReadyCallback) {
                    this.userInfoReadyCallback(res)
                  }
                }
              })
            }
          },
        }) */
    //获取分享信息数据
    wx.showShareMenu({
      withShareTicket: true
    })

  },


  //luyou
  onShow() {
    console.log('onShow')
  },
  onHide() {
    console.log('onHide')
  },





  //获取微信用户信息
  getUserInfo() {
    var that = this
    wx.login({
      success: function (res) {
        var code = res.code;
        console.log("----------code is --------");
        console.log(res);


        //放置全局变量
        that.globalData.code = code;

        //开发者服务器使用登录凭证code获取openid
        //发送 res.code 到后台换取 openId, sessionKey, unionId
        //that.getOpenId(code);


        //获取微信用户信息
        var self = that
        wx.getUserInfo({
          success: function (res) {
            console.log("---------- wx.login  success --------")
            console.log(res.userInfo)

            //放置全局变量
            self.globalData.hasUserInfo = true;
            self.globalData.userInfo = res.userInfo

            //将数据存储在本地缓存中
            try {
              wx.setStorageSync('userInfo', res.userInfo)
            } catch (e) {
              console.log(e)
            }
          },
          fail: function (res) {
            self.globalData.hasUserInfo = false;
            self.globalData.userInfo = null;
            try {
              wx.setStorageSync('userInfo', null)
            } catch (e) {
              console.log(e)
            }
          }
        })

      },
      fail: function (res) {
        this.globalData.hasUserInfo = false;
        this.globalData.userInfo = null;
        try {
          wx.setStorageSync('userInfo', null)
        } catch (e) {
          console.log(e)
        }
      }
    })
  },





  //获取用户经纬度和地理信息
  getLocation: function (e) {
    var that = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log("-----" + JSON.stringify(res))
        that.globalData.locationInfo = res

        const data = {
          ak: that.globalData.ak,
          location: res.latitude + "," + res.longitude,
          output: 'json',
          coordtype: 'wgs84'
        }
        var self = that
        Api.getAddressByLocation({
          data,
          success: (res) => {
            console.log("---------- 取得地理信息 ----------")
            console.log(res.data)

            if (res.data.status != '220') {
              self.globalData.city = res.data.result.addressComponent.city



              console.log(res.data.result.addressComponent.city)

              /*
              console.log(res.data.result.addressComponent.city_level)
              console.log(res.data.result.addressComponent.country_code)
              console.log(res.data.result.addressComponent.country_code_iso)
              console.log(res.data.result.addressComponent.province)
              console.log(res.data.result.addressComponent.street)
              console.log(res.data.result.addressComponent.street_number)
              */

              self.globalData.CurrentDetailAddress = res.data.result.addressComponent.city + res.data.result.addressComponent.street

            }
          }
        })

      }
    })
  },



  //退出登录
  userSignOut() {
    console.log("-------signOut-----------")
    try {
      wx.clearStorageSync()
      this.globalData.memberInfo = null
      this.globalData.userInfo = null
      this.globalData.hasLogin = false
      //app.globalData.hasUserInfo = false
      this.globalData.city = null
      this.globalData.CurrentDetailAddress = null

      wx.switchTab({
        url: '/pages/index/index'
      })

    } catch (e) {
      // Do something when catch error
    }

  },




  WxValidate: (rules, messages) => new WxValidate(rules, messages),


  WxService: new WxService,


})
